<template>
  <nav class="navbar">
    <div class="container">
      <div class="logo">
        ICOOLKJ
      </div>
      <ul class="nav-links">
        <li v-for="(item, index) in navItems" :key="index">
          <router-link
              :to="item.href"
              :class="{ active: currentActive === index }"
              @mouseenter="handleMouseEnter(index)"
              @mouseleave="handleMouseLeave()"
              @click="handleClick(index)"
          >
            {{ item.title }}
          </router-link>
        </li>
      </ul>
      <div class="login-register">
        <router-link to="/login">登录</router-link> / <router-link to="/register">注册</router-link>
      </div>
    </div>
  </nav>
</template>

<script setup>
import { ref, watchEffect } from 'vue';
import { useRouter, useRoute } from 'vue-router';

const navItems = [
  {title: '首页', href: '/'},
  {title: '课程中心', href: '/course-center'},
  {title: '题库', href: '/question-bank'},
  {title: '名师', href: '/teachers'},
  {title: '问答', href: '/qa'},
  {title: '经典案例', href: '/cases'},
  {title: '关于我们', href: '/about'},
  {title: '加入我们', href: '/join-us'},
];

const currentActive = ref(0);
const hoverIndex = ref(-1);
const router = useRouter();
const route = useRoute();

// 监听路由变化，更新 currentActive
watchEffect(() => {
  const currentPath = route.path;
  if (currentPath === '/login' || currentPath === '/register') {
    currentActive.value = -1; // 登录或注册页面，不选中任何菜单项
  } else {
    const index = navItems.findIndex(item => item.href === currentPath);
    if (index !== -1) {
      currentActive.value = index;
    }
  }
});

const handleMouseEnter = (index) => {
  hoverIndex.value = index;
};

const handleMouseLeave = () => {
  hoverIndex.value = -1;
};

const handleClick = (index) => {
  currentActive.value = index;
  router.push(navItems[index].href);
};
</script>

<style scoped>
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #e0f2f1;
  z-index: 1000;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.logo {
  font-weight: bold;
}

.nav-links {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
}

.nav-links li {
  margin: 0 10px;
}

.nav-links a {
  color: #333;
  text-decoration: none;
  transition: color 0.3s ease;
}

.nav-links a:hover {
  color: red;
}

.nav-links a.active {
  font-weight: bold;
  color: red;
}

.login-register {
  display: flex;
  align-items: center;
}

.login-register a {
  color: #333;
  text-decoration: none;
  margin: 0 5px;
}
</style>